package com.example.tabbar.fragment

import android.app.Activity
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import com.example.tabbar.R
import com.example.tabbar.databinding.FragmentEditUserBinding
import com.example.tabbar.utils.CustomSpinner
import com.junray.usermangement.Const
import com.junray.usermangement.room.bean.UserAndRole
import com.junray.usermangement.room.entity.Permission
import com.junray.usermangement.room.entity.Role
import com.junray.usermangement.room.entity.Rule
import com.junray.usermangement.room.entity.User
import com.junray.usermangement.utils.LiveDataUtils.observeOnce
import com.junray.usermangement.utils.SessionManager
import com.junray.usermangement.utils.SessionManager.Companion.instance
import com.junray.usermangement.utils.TimeUtils
import com.junray.usermangement.utils.TimeUtils.getFutureTime
import com.junray.usermangement.viewModel.UserViewModel
import java.util.concurrent.atomic.AtomicInteger


class EditUserFragment : Fragment() {
    private var binding: FragmentEditUserBinding? = null
    private var isPasswordVisible = false
    private var isConfirmPasswordVisible = false
    private var selectRole :TextView ? = null
    private var userId: Long? = null // 添加用户ID字段
    private var viewmodel: UserViewModel? = null
    private var name : EditText? = null
    private var password: EditText? = null
    private var confirmPassword : EditText? = null
    private var roleId : Long? = null
    private var oldRoleId :Long? = null

    private val activity: Activity by lazy { requireActivity() }
    private var roleItems = arrayListOf<String>()
    private var roleMap = mutableMapOf<String, Long>()
    private var user: User ? = null
    private var currentUser:User? = null
    private var sessionManager:SessionManager? = null
    private var passwordMinLength = Const.PASSWORD_MIN_LENGTH
    private var currentRule: Rule? = null

    // 当前用户角色权限等级
    private var currentRoleLevel : Int? = null
    // 编辑用户角色等级
    private var userLevel : Int = -1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            val id = it.getLong(ARG_USER_ID, -1)
            val level = it.getInt(ARG_USER_LEVEL, -1)
            if (id != -1L) {
                userId = id
                userLevel =  level
            }

        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentEditUserBinding.inflate(inflater, container, false)
        return binding?.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()

        setView()
        //设置角色下拉框
        setRoleSpinner()

        onClick()

        setupPasswordToggles()
    }

    private fun initView() {
        viewmodel = ViewModelProvider(this)[(UserViewModel::class.java)]
        selectRole = binding!!.selectRole
        name = binding?.etUserName
        password = binding?.password
        confirmPassword = binding?.surePwd

        sessionManager = instance

        currentUser = sessionManager?.currentUser
        currentRule = sessionManager?.currentRule
        currentRoleLevel = sessionManager?.currentRoleLevel
        if (currentUser == null) {
            Log.d("user", "user: 当前用户为空")
        }
    }

    private fun onClick() {
        binding!!.editBack.setOnClickListener {
            // 返回上一页
            parentFragmentManager.popBackStack()
        }
        //添加或者编辑用户
        binding?.userSave?.setOnClickListener {
            //新建或者更新用户  根据userId去判断
            saveUser()
        }
    }

    private fun setView() {
        if (userId == null) {
            // 新建用户
            setupForNewUser()
        } else {
            // 编辑用户
            setupForEditUser()
            observeOnce(viewmodel!!.getUserAndRole(userId!!), viewLifecycleOwner) { item : UserAndRole?  ->
                if (item != null) {
                    user = item.user
                    name?.setText(item.user.username)
                    oldRoleId = item.role.id
                }
            }
        }
    }

    private fun saveUser() {
        val username = name?.text.toString().trim()
        val password = password?.text.toString().trim()
        val confirmPassword = confirmPassword?.text.toString().trim()
        val roleName = selectRole?.text.toString().trim()
        if (userId == null) {
            if (!validateInput(username, password, confirmPassword, roleName,false)) {
                return
            }
            // 检查密码复杂度
            if (!validatePasswordComplexity(password)) {
                return
            }

            checkUserName(username,password)
        } else {
            if (!validateInput(username, password, confirmPassword, roleName, true)) {
                return
            }
            // 检查用户名是否已存在（排除当前用户）
            checkUserNameForUpdate(username, password)
        }
    }

    private fun validateInput(
        username: String,
        password: String,
        confirmPassword: String,
        roleName: String,
        isUpdate: Boolean
    ): Boolean {
        if (!isUpdate &&  username.isEmpty()) {
            Toast.makeText(activity, R.string.tb_username_not_null, Toast.LENGTH_SHORT).show()
            return false
        }

        // 超级管理员用户名检查
        if (username == Const.SUPER_ADMIN_USERNAME && (!isUpdate || userId != Const.SUPER_ADMIN_USER_ID)) {
            Toast.makeText(
                activity,
                com.junray.usermangement.R.string.um_error_username_not_use,
                Toast.LENGTH_SHORT
            ).show()
            return false
        }
        // 角色检查
        roleId = roleMap[roleName]
        if (roleId == null) {
            Toast.makeText(activity, R.string.tb_select_role_invalid, Toast.LENGTH_SHORT).show()
            return false
        }

        // 密码一致性检查（仅在创建时或更新时输入了密码）
        if (!isUpdate) {
            if (password.isEmpty() || confirmPassword.isEmpty()) {
                Toast.makeText(activity, R.string.tb_pwd_edittext_not_null, Toast.LENGTH_SHORT).show()
                return false
            }

            if (password != confirmPassword) {
                Toast.makeText(activity, R.string.tb_enter_pwd_different, Toast.LENGTH_SHORT).show()
                return false
            }
        } else {
            if (password.isNotEmpty() && password != confirmPassword) {
                Toast.makeText(activity, R.string.tb_enter_pwd_different, Toast.LENGTH_SHORT).show()
                return false
            }
        }

        return true
    }

    private fun validatePasswordComplexity(password: String): Boolean {

        if (currentRule != null) {
            val pwdLength = currentRule!!.pwdLength
            if (pwdLength != 0) {
                passwordMinLength = pwdLength
            }
        }

        if (password.length < passwordMinLength) {
            val msg = String.format(
                getString(com.junray.usermangement.R.string.um_error_pwd_length),
                passwordMinLength
            )
            Toast.makeText(requireContext(), msg, Toast.LENGTH_SHORT).show()
            return false
        }

        if (!sessionManager!!.complexPassword(password)) {
            Toast.makeText(
                requireContext(),
                com.junray.usermangement.R.string.um_pwd_not_complex,
                Toast.LENGTH_SHORT
            ).show()
            return false
        }

        return true
    }
    private fun checkUserNameForUpdate(username: String, password: String) {
        observeOnce(
            viewmodel!!.countByUsername(username), viewLifecycleOwner
        ) { count: Int? ->
            if (count != null && count > 0) {
                // 如果存在同名用户，检查是否是当前用户自己
                observeOnce(
                    viewmodel!!.getUserByUsername(username), viewLifecycleOwner
                ) { existingUser: User? ->
                    if (existingUser != null && existingUser.id != user?.id) {
                        // 存在其他用户使用此用户名
                        Toast.makeText(
                            activity,
                            com.junray.usermangement.R.string.um_error_username_exists,
                            Toast.LENGTH_SHORT
                        ).show()
                    } else {
                        performUpdateUser(username, password)
                    }
                }
            } else {
                // 用户名不存在，可以安全更新
                performUpdateUser(username, password)
            }
        }
    }

    private fun performUpdateUser(username: String, password: String) {
        // 处理密码更新逻辑
        if (password.isNotEmpty()) {
            // 密码规则校验
            if (!validatePasswordComplexity(password)) {
                return
            }
            // 如果输入了密码，则更新密码和可能的用户名
            if (username != user?.username) {
                // 同时更新用户名和密码
                viewmodel!!.updatePasswordWithUsername(
                    user!!.id,
                    password,
                    username
                )
                Toast.makeText(activity, R.string.tb_update_name_pwd_success, Toast.LENGTH_SHORT).show()
            } else {
                viewmodel!!.updatePassword(user!!.id, password)
                Toast.makeText(activity, R.string.tb_update_pwd_success, Toast.LENGTH_SHORT).show()
            }
        } else {
            // 没有输入密码，只更新用户名（如果需要）
            if (username != user?.username) {
                // 更新用户名
                viewmodel!!.updateUsername(user!!.id, username)
                Toast.makeText(activity, R.string.tb_update_name_success, Toast.LENGTH_SHORT).show()
            }
        }

        // 更新用户角色关联表
        if (roleId != oldRoleId && oldRoleId != null) {
            viewmodel!!.updateUserRole(user!!.id, roleId!!)
        }

        // 返回上一页
        parentFragmentManager.popBackStack()
    }

    // 检查用户名是否存在
    private fun checkUserName(username: String, passwords: String) {
        // 检查用户名是否已存在
        observeOnce(
            viewmodel!!.countByUsername(username), viewLifecycleOwner
        ) { count: Int? ->
            if (count != null && count > 0) {
                Toast.makeText(
                    activity,
                    com.junray.usermangement.R.string.um_error_username_exists,
                    Toast.LENGTH_SHORT
                ).show()
            } else {
                val currentTime = TimeUtils.currentTime
                val user = if (sessionManager!!.isSuperAdmin) {
                    User(username, -1, passwords, currentTime)
                } else {
                    User(username, currentUser!!.id, passwords, currentTime)
                }
                if (currentRule == null) {
                    currentRule = Rule()
                }

                if (!currentRule?.pwdValid.isNullOrEmpty()) {
                    try {
                        val longTime = currentRule?.pwdValid!!.toLong()
                        val time = getFutureTime(longTime)
                        user.pwdValid = time
                    } catch (e: NumberFormatException) {
                        user.pwdValid = null
                    }
                } else {
                    user.pwdValid = null
                }
                user.pwdFailures = currentRule!!.pwdFailures

                viewmodel?.createUser(user, listOf(roleId!!))
                Toast.makeText(activity, R.string.tb_add_user_success, Toast.LENGTH_SHORT).show()
                parentFragmentManager.popBackStack()
            }
        }
    }

    private fun setupForNewUser() {
        binding?.editTitle?.text = getString(R.string.tb_setting_add_user)
        binding?.signatureView?.visibility = View.GONE

        // 新建用户时也只显示权限相同或更少的角色
        filterAndLoadRoles()
    }


    private fun setupForEditUser() {
        binding?.editTitle?.text = getString(R.string.tb_setting_edit_user)
        binding?.signatureView?.visibility = View.VISIBLE

        // 编辑用户时也只显示权限相同或更少的角色
        filterAndLoadRoles()
    }

    private fun setRoleSpinner() {

        val customSpinner = CustomSpinner(requireContext(), roleItems) { _, item ->
            selectRole?.text = item
            roleId = roleMap[item]
        }
        customSpinner.setOnDismissListener {
            selectRole?.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.to_down, 0)
        }

        selectRole?.setOnClickListener {
            selectRole?.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.to_up, 0)
            val currentText = selectRole?.text.toString()
            val position = roleItems.indexOf(currentText)
            if (position >= 0) {
                customSpinner.setSelectedPosition(position)
            }
            customSpinner.show(selectRole!!)
        }
    }
    private fun filterAndLoadRoles() {
        // 获取当前用户的角色和权限信息
        if (sessionManager!!.isSuperAdmin) {
            viewmodel?.allRoles?.observe(viewLifecycleOwner) { allRoles : List<Role>->
                updateRoleItems(allRoles)
            }
        } else {
            // 获取并过滤角色
            filterRolesWithPermissions()
        }

    }

    private fun filterRolesWithPermissions() {
        observeOnce(viewmodel?.allRoles!!, viewLifecycleOwner) { allRoles ->
            // 如果是超级管理员，显示所有角色
            if (sessionManager?.isSuperAdmin == true) {
                updateRoleItems(allRoles)
                return@observeOnce
            }

            val filteredRoles = mutableListOf<Role>()

            val currentUserRoleLevel = currentRoleLevel ?:4
            // 过滤掉比自身角色权限级别高的角色
            val levelFilteredRoles = if (userId == null ) {
                // 新建用户：只显示权限级别更低的角色（数字更大）
                allRoles.filter { role ->
                    role.level > currentUserRoleLevel
                }
            }else {
                allRoles.filter { role ->
                    // 编辑用户：只显示权限级别低于当前用户角色级别的角色
                    role.level > currentUserRoleLevel || role.level == userLevel
                }
            }

            if (levelFilteredRoles.isEmpty()) {
                updateRoleItems(filteredRoles)
                return@observeOnce
            }


            for (role in levelFilteredRoles) {
                filteredRoles.add(role)
            }
            // 去重并更新UI
            val distinctRoles = filteredRoles.distinctBy { it.id }.sortedBy { it.id }
            updateRoleItems(distinctRoles)
        }
    }

    private fun updateRoleItems(roles: List<Role>) {
        roleItems.clear()
        roleMap.clear()

        roles.forEach { role ->
            val roleName = role.name ?: ""
            roleItems.add(roleName)
            roleMap[roleName] = role.id
        }

        // 更新选中值
        if (roleItems.isNotEmpty() && userId != null) {
            // 编辑模式下设置当前用户的角色为选中状态
            observeOnce(viewmodel!!.getUserAndRole(userId!!), viewLifecycleOwner) { userAndRole: UserAndRole? ->
                userAndRole?.role?.let { role ->
                    selectRole?.text = role.name
                    roleId = role.id
                }
            }
        } else if (roleItems.isNotEmpty()) {
            // 新建用户模式下，默认选中第一个角色
            selectRole?.text = roleItems[0]
            roleId = roleMap[roleItems[0]]
        } else {
            // 处理 roleItems 为空的情况
            selectRole?.text = ""
            roleId = null
        }
    }


    private fun setupPasswordToggles() {
        // 密码输入框切换
        binding?.passwordToggle?.setOnClickListener {
            isPasswordVisible = !isPasswordVisible
            togglePasswordVisibility(binding?.password, isPasswordVisible, binding?.passwordToggle)
        }

        // 确认密码输入框切换
        binding?.confirmPasswordToggle?.setOnClickListener {
            isConfirmPasswordVisible = !isConfirmPasswordVisible
            togglePasswordVisibility(binding?.surePwd, isConfirmPasswordVisible, binding?.confirmPasswordToggle)
        }
    }

    private fun togglePasswordVisibility(
        editText: EditText?,
        isVisible: Boolean,
        toggleButton: ImageView?
    ) {
        if (isVisible) {
            editText?.inputType = android.text.InputType.TYPE_CLASS_TEXT or
                    android.text.InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
            toggleButton?.setImageResource(R.drawable.pwd_isshow) // 显示眼睛图标
        } else {
            editText?.inputType = android.text.InputType.TYPE_CLASS_TEXT or
                    android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD
            toggleButton?.setImageResource(R.drawable.pwd_unshow) // 隐藏眼睛图标
        }

        // 保持光标在文本末尾
        editText?.setSelection(editText.text.length)
    }

    companion object {
        private const val ARG_USER_ID = "user_id"
        private const val ARG_USER_LEVEL = "user_level"
        @JvmStatic
        fun newInstance(userId: Long? = null, userLevel: Int? = null) =
            EditUserFragment().apply {
                arguments = Bundle().apply {
                    if (userId != null ) {
                        putLong(ARG_USER_ID, userId)
                        putInt(ARG_USER_LEVEL, userLevel ?: -1)
                    }
                }
            }
    }
}